<?php

namespace app\api\controller\shop;


use addons\epay\library\Service;
use app\admin\model\Cmdlog;
use app\admin\model\Org;
use app\admin\model\Roomclean;
use app\admin\model\Shopdevice;
use app\admin\model\Shopdiscount;
use app\admin\model\Shopmno;
use app\admin\model\Shoporder;
use app\admin\model\Shoporderprofit;
use app\admin\model\Shoproom;
use app\admin\model\Shoproombook;
use app\admin\model\Shoptuan;
use app\admin\model\Userbalance;
use app\admin\model\Userdiscount;
use app\admin\model\Userorderprofit;
use app\admin\model\Usertuan;
use app\api\service\DeviceService;
use app\api\service\VbillService;
use app\common\controller\Api;
use Yansongda\Pay\Pay;

/**
 *
 */
class Order extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];


    public function getList(){


        $shop_id = $this->request->param('shop_id');
        $shopOrderModel = new Shoporder();
        $page = $this->request->param('page');
        $status = $this->request->param('status');
        $orderNo = $this->request->param('orderNo');
        $startTime = $this->request->param('startTime');
        $roomId = $this->request->param('roomId');

        $limit = 10;
        $offset = ($page - 1) * $limit;

        $where = array();
        $where['shop_id'] = $shop_id;
        if($status != ''){
            $where['Shoporder.status'] = array('=',$status);
        }
        if($roomId != ""){
            $where['Shoporder.room_id'] =$roomId;

        }
        if($orderNo != ""){
            if(strlen($orderNo) == 11){
                $userModel = new \app\admin\model\User();
                $user = $userModel->where('mobile',$orderNo)->find();
                if($user){
                    $where['Shoporder.user_id'] =$user['id'];
                }
            }else{
                $where['order_no'] =array('like', "%" . $orderNo . "%");
            }
        }
        if($startTime != "" && $startTime != "时间选择" ){
            $start = strtotime($startTime." 00:00");
            $end = strtotime($startTime." 23:59");
            $where['create_time'] = array("between",array($start,$end));
        }
        $list =  $shopOrderModel->with(['user'])->where('Shoporder.status',"<>",'paying')->where($where)->order('create_time','desc')->limit($offset,$limit)->select();
        foreach ($list as $key=>$val){

            $val['user']->hidden(['password', 'salt']);
            $list[$key]['order_no_str'] = substr($val['order_no'],0,5)."*****".substr($val['order_no'],strlen($val['order_no'])-4,4);

            $list[$key]['book_start'] = date("Y-m-d H:i:s",$val['book_start']);
            $list[$key]['book_end'] = date("Y-m-d H:i:s",$val['book_end']);
            $list[$key]['status_txt'] = $shopOrderModel->formatStatus($val['status']);
        }
        $this->success('',$list);
    }


    public function detail(){

        $order_no = $this->request->param("order_no");
        $shopOrderModel = new Shoporder();
        $order = $shopOrderModel->with(['user'])->where('order_no',$order_no)->find();
        $order['tuan'] = "";
        if($order['tuan_id'] != -1){
            $userTuanModel = new Usertuan();
            $userTuan = $userTuanModel->where('id',$order['tuan_id'])->find();
            $shopTuanModel = new Shoptuan();
            $tuan = $shopTuanModel->where('id',$userTuan['tuan_id'])->find();
            if($tuan){
                $order['tuan'] = $tuan['name'];
            }
        }
        $order['discount_name'] = "";
        $order['discount_desc'] = "";
        if($order['discount_id'] > 0){
            $userDiscountModel = new Userdiscount();
            $shopDiscountModel = new Shopdiscount();

            $userDiscount = $userDiscountModel->where('id',$order['discount_id'])->find();
            $shopDiscount = $shopDiscountModel->where('id',$userDiscount['discount_id'])->find();
            if($shopDiscount['discount_type'] == '时长抵扣'){
                $order['discount_desc'] =  "时长抵扣:".$shopDiscount['discount_val']."小时";
            }else if($shopDiscount['discount_type'] == '金额抵扣'){
                $order['discount_desc'] =  "金额抵扣:".$shopDiscount['discount_val']."元";

            }else{
                $order['discount_desc'] =  "折扣抵扣:".$shopDiscount['discount_val']."折";
            }
            $order['discount_name'] = $shopDiscount['name'];

        }

        if($order['mt_code'] != ""){

        }
        if($order['dou_code'] != ""){

        }

        $order['user']->hidden(['password', 'salt']);

        $order['status_txt'] = $shopOrderModel->formatStatus($order['status']);
        $order['book_start'] = date("Y-m-d H:i:s",$order['book_start']);
        $order['book_end'] = date("Y-m-d H:i:s",$order['book_end']);
        $this->success('',$order);
    }



    public function refund(){

        $order_no = $this->request->param('order_no');
        $amount = $this->request->param('amount');
        $shopOrderModel = new Shoporder();
        $order = $shopOrderModel->where('order_no',$order_no)->find();
//        if($order['status'] != 'payed'){
//            $this->error("此订单状态不允许退款");
//        }
        if($amount == 0){
            $this->error("退款金额不能为0");
        }
        $user = $this->auth->getUser();
        $shopModel = new \app\admin\model\Shop();
        $shop = $shopModel->where('id',$order['shop_id'])->find();
        if($shop['user_id'] != $user['id']){
            $this->error("您没有权限操作退款");
        }

        $backBalanceAmount = 0;
        if($order['balance']>=$amount){
            $refundAmount = 0;
            $backBalanceAmount = $amount;
        }else{
            $refundAmount = $amount-$order['balance'];
            $backBalanceAmount = $order['balance'];
        }

        if($order['pay_amount'] >0 && $refundAmount>0){


            $refundOrder_no = getOrderSn();
            $orderParam = [
                'out_trade_no' => $order['order_no'],
                'out_refund_no' => $refundOrder_no,
                'total_fee' => $order['pay_amount'] * 100,
                'refund_fee' => $refundAmount* 100,
                'refund_desc' => '预定退款',
            ];



            $orgModel = new Org();
            $org = $orgModel->where('id',$order['org_id'])->find();

            $shopMnoModel = new Shopmno();
            $shopMno = $shopMnoModel->where('shop_id',$order['shop_id'])->find();
            $mno = $org['mno'];
            if($shopMno && $shopMno['ratio'] == 100){
                $mno = $shopMno['mno'];
            }
            $req = array();
            $req['mno']= $mno;
            $req['ordNo']= $refundOrder_no;
            $req['origOrderNo']= $order['order_no'];
            $req['amt']=$refundAmount;


            $vbillService = new VbillService();
            $ret = $vbillService->refund($req);
            error_log("====refund===".$ret);
            $result = json_decode($ret,true);
            if($result['respData']['bizCode'] != "0000"){
                $this->error($result['respData']['bizMsg']);
            }
            $shopOrderModel->where('id',$order['id'])->update(['status'=>'refund','refund_order_no'=>$refundOrder_no,'update_time'=>time()]);
        }else{
            $shopOrderModel->where('id',$order['id'])->update(['status'=>'refund','update_time'=>time()]);
        }
        //退余额
        if($order['balance'] >0){
            $userBalanceModel = new Userbalance();
            $balanceDb = $userBalanceModel->where('user_id',$order['user_id'])->where('order_id',$order['id'])->where('type','out')->find();
            $userBalanceModel->insert(['user_id'=>$balanceDb['user_id'],'type'=>'in','amount'=>$backBalanceAmount,'mark'=>'订单退款','create_time'=>time(),
                'shop_id'=>$balanceDb['shop_id'],'order_id'=>$balanceDb['order_id'],'b_type'=>'refund']);
        }
        //退商家分润 ，代理商分润
        if($order['pay_amount'] >0){
            $shopOrderProfitModel =new Shoporderprofit();
            $shopOrderProfitModel->where('order_id',$order['id'])->where('user_id',$shop['user_id'])->delete();

            $userOrderProfitModel = new Userorderprofit();
            $userOrderProfitModel->where('user_id',$shop['agent_id'])->where('order_id',$order['id'])->delete();
        }

        //团购券
        if($order['tuan_id'] != -1){
            $userTuanModel = new Usertuan();
            $userTuanModel->where('order_id',$order['id'])->update(['status'=>'unuse']);
        }

        //恢复预定
        $roomBookOrderModel = new Shoproombook();
        $roomBookOrderModel->where('order_id',$order['id'])->delete();

        $cleanRoomModel = new Roomclean();
        $cleanRoomModel->where('order_id',$order['id'])->delete();


        $this->success('退款成功');


    }

    public function updateOrderBookTime(){

        $order_no = $this->request->param('order_no');
        $time = $this->request->param('time');
        $shopOrderModel = new Shoporder();
        $order = $shopOrderModel->where('order_no',$order_no)->find();
        if($order['status']  != 'payed'){
            $this->error("此订单已开始或者已完成，不支持更改");
        }

        $hour = ($order['book_end'] - $order['book_start']) / 3600;

        $time1 = strtotime($time);
        if($time1 <= time()){
            $this->error("选择开始时间 要大于现在的时间");
        }

        $min = $hour * 60+30;//也包含保洁的时间
        $min2 = $hour * 60;
        $time2 = strtotime("+".$min." minute",$time1);
        $bookEnd = strtotime("+".$min2." minute",$time1);

        $cleanStart = strtotime("+30 minute",$bookEnd);


        $shopRoomBookModel = new Shoproombook();
        $checkStart = $shopRoomBookModel->where('order_id',"<>",$order['id'])->where('status', 'in', ['undo', 'doing'])->where('room_id', $order['room_id'])->where('start_time', "<=", $time1)->where("end_time", ">=", $time1)->find();
        $checkEnd = $shopRoomBookModel->where('order_id',"<>",$order['id'])->where('status', 'in', ['undo', 'doing'])->where('room_id', $order['room_id'])->where('start_time', "<=", $time2)->where("end_time", ">=", $time2)->find();
        $checkEnd3= $shopRoomBookModel->where('order_id',"<>",$order['id'])->where('status', 'in', ['undo', 'doing'])->where('room_id', $order['room_id'])->where('start_time', ">=", $time1)->where("end_time", "<=", $time2)->find();

        if ($checkStart != null || $checkEnd != null || $checkEnd3 != null) {

            $this->error("此时间段已预定，不能更改订单时间");
        }

        $shopCleanModel = new Roomclean();
        $shopOrderModel->where('id',$order['id'])->update(['book_start'=>$time1,'book_end'=>$bookEnd]);
        $shopRoomBookModel->where('order_id',$order['id'])->update(['start_time'=>$time1,'end_time'=>$bookEnd]);
        $shopCleanModel->where('order_id',$order['id'])->update(['start_time'=>$bookEnd,'end_time'=>$cleanStart]);

        $this->success('成功');
    }


    /**
     * 赠送时间
     */
    public function sendOrderTime(){

        $user = $this->auth->getUser();
        $order_no = $this->request->param('order_no');
        $hour = $this->request->param('hour');
        $shopOrderModel = new Shoporder();
        $order = $shopOrderModel->where('order_no',$order_no)->find();
        if($order['status']  == 'done'){
            $this->error("此订单已结束，不支持续时");
        }


        $time1 = $order['book_end'];

        $min = $hour * 60+30;//也包含保洁的时间
        $min2 = $hour * 60;
        $time2 = strtotime("+".$min." minute",$time1);
        $bookEnd = strtotime("+".$min2." minute",$time1);

        $cleanStart = strtotime("+30 minute",$bookEnd);


        $shopRoomBookModel = new Shoproombook();
        $checkStart = $shopRoomBookModel->where('status', 'in', ['undo', 'doing'])->where('room_id', $order['room_id'])->where('start_time', "<", $time1)->where("end_time", ">", $time1)->find();
        $checkEnd = $shopRoomBookModel->where('status', 'in', ['undo', 'doing'])->where('room_id', $order['room_id'])->where('start_time', "<", $time2)->where("end_time", ">", $time2)->find();
        $checkEnd3= $shopRoomBookModel->where('status', 'in', ['undo', 'doing'])->where('room_id', $order['room_id'])->where('start_time', ">", $time1)->where("end_time", "<", $time2)->find();

        if ($checkStart != null || $checkEnd != null || $checkEnd3 != null) {

            $this->error("此时间段已预定，不能续费时间");
        }


//        $checkStart = $shopRoomBookModel->where('status', 'in', ['undo', 'doing'])->where('room_id', $order['room_id'])->where('start_time', "<=", $time1)->where("end_time", ">=", $time2)->find();
//        $checkEnd = $shopRoomBookModel->where('status', 'in', ['undo', 'doing'])->where('room_id', $order['room_id'])->where('start_time', ">=", $time1)->where('start_time', "<=", $time2)->where("end_time", ">=", $time2)->find();
//        $checkEnd3 = $shopRoomBookModel->where('status', 'in', ['undo', 'doing'])->where('room_id', $order['room_id'])->where('start_time', "<=", $time1)->where("end_time", ">=", $time1)->where("end_time", "<=", $time2)->find();
//        $checkEnd4 = $shopRoomBookModel->where('status', 'in', ['undo', 'doing'])->where('room_id', $order['room_id'])->where('start_time', ">=", $time1)->where("end_time", "<=", $time2)->find();
//
//
//        if ($checkStart != null || $checkEnd != null || $checkEnd3 != null || $checkEnd4 != null) {
//            $this->error("此时间段已被预定");
//        }
//
        $shopRoomBookModel = new Shoproombook();
        $roomBook = $shopRoomBookModel->where('order_id',$order['id'])->find();

        $shopCleanModel = new Roomclean();
        $shopOrderModel->where('id',$order['id'])->update(['book_end'=>$bookEnd]);
        $shopRoomBookModel->where('order_id',$order['id'])->update(['end_time'=>$bookEnd]);
        $shopCleanModel->where('order_id',$order['id'])->update(['start_time'=>$bookEnd,'end_time'=>$cleanStart]);

        if($roomBook['start_time'] >time() && $roomBook['status'] == 'undo'){


            $this->success('');
        }


        if($roomBook['status'] == 'doing' || $roomBook['status'] == 'undo'){


            if($roomBook['status'] == 'undo'){
                $shopRoomBookModel->where('id',$roomBook['id'])->update(['status'=>'doing']);
            }
            $minute=floor(($bookEnd-time())%86400/60);

            //自动发送cmd 续费指令
            $shopDeviceModel = new Shopdevice();

            $newOrderNo = getOrderSn();
            $shopOrderModel->where('id',$order['id'])->update(['order_no'=>$newOrderNo]);

            $device =$shopDeviceModel->where('room_id',$order['room_id'])->find();
            $sn = $device['sn'];
            $req = array();
            $req['sec'] = $minute*60;
            $req['orderNo'] = $newOrderNo;
            $req['sn'] = $sn;
            $req['voice'] = "";


            if($device['prod'] == 1) {

                $ret = http_post_json($this->openCmdUrl, json_encode($req));
                $ret = json_decode($ret, true);
            }else{
                $deviceService = new DeviceService();
                $doorReq = array();
                $doorReq['open'] = 1;
                $doorReq['open2'] = 1;
                $doorReq['open3'] = 1;
                $doorReq['open4'] = 1;
                $doorReq['device_sn'] = $device['device_sn'];

                $timeReq = array();
                $timeReq['device_sn'] = $device['device_sn'];
                $timeReq['sec'] =$minute*60 ;
                $timeReq['time'] = time();
                $deviceService->dxIotDoor($doorReq);
                $deviceService->dxIotTime($timeReq);
                $ret = array();
            }


           // error_log("=====send====".json_encode($req));
            $cmdModel = new Cmdlog();
            $cmdModel->insert(['user_id' => $user['id'], 'cmd' => json_encode($req),
                'create_time' => time(),'order_no'=>$newOrderNo,'shop_id'=>$order['shop_id'],'room_id'=>$order['room_id']]);
            $this->success('成功',$ret);

        }else{
            $this->error("此订单不是进行中订单，不可续时");
        }


    }


    public function setRoom(){



        $room_id = $this->request->param('room_id');
        $order_no = $this->request->param('order_no');
        $shopOrderModel = new Shoporder();
        $order = $shopOrderModel->where('order_no',$order_no)->find();
        if($order['status']  == 'done'){
            $this->error("此订单已结束，不支持更换");
        }
        if($room_id == $order['room_id']){
            $this->error("此订单包厢 就是该包厢 不支持更换");
        }
        $time1 = $order['book_start'];
        $time2 = $order['book_end'];

        $deviceModel = new Shopdevice();
        $oldDevice = $deviceModel->where('room_id',$order['room_id'])->find();


        $shopRoomBookModel = new Shoproombook();
        $checkStart = $shopRoomBookModel->where('status', 'in', ['undo', 'doing'])->where('room_id', $room_id)->where('start_time', "<", $time1)->where("end_time", ">", $time1)->find();
        $checkEnd = $shopRoomBookModel->where('status', 'in', ['undo', 'doing'])->where('room_id', $room_id)->where('start_time', "<", $time2)->where("end_time", ">", $time2)->find();
        $checkEnd3= $shopRoomBookModel->where('status', 'in', ['undo', 'doing'])->where('room_id', $room_id)->where('start_time', ">", $time1)->where("end_time", "<", $time2)->find();

        if ($checkStart != null || $checkEnd != null || $checkEnd3 != null) {

            $this->error("此时间段已预定，不能续费时间");
        }


        $shopRoomModel = new Shoproom();
        $room = $shopRoomModel->where('id',$room_id)->find();
        $shopOrderModel->where('id',$order['id'])->update(['room_id'=>$room_id,'room_name'=>$room['name']]);
        $shopRoomModel->where('id',$room_id)->update(['status'=>'busy']);
        $shopRoomModel->where('id',$order['room_id'])->update(['status'=>'free']);

        $shopRoomBookModel = new Shoproombook();
        $shopCleanModel = new Roomclean();
        $shopCleanModel->where('order_id',$order['id'])->update(['room_id'=>$room_id]);
        $shopRoomBookModel->where('order_id',$order['id'])->update(['room_id'=>$room_id]);


        $req = array();
        $req['orderNo'] = $order_no;
        $req['sn'] = $oldDevice['sn'];
        $req['sec'] = 0;
        $req['voice'] = "";

        if(time()>= $time1 && time()<= $time2){
            $db = array();
            $db['order_no'] = $order_no;
            $db['shop_id'] = $order['shop_id'];
            $db['room_id'] = $order['room_id'];
            $db['user_id'] = $this->auth->getUser()['id'];
            $db['create_time'] = time();
            $db['cmd'] = json_encode($req);
            $cmdModel = new Cmdlog();
            $cmdModel->insert($db);


            $ret = http_post_json($this->openCmdUrl, json_encode($req));
            $ret = json_decode($ret, true);
        }



        $shopOrderModel->where('id',$order['id'])->update(['order_no'=>getOrderSn()]);

        $this->success('修改成功');

    }

}
